
package com.networklib.http.interceptor;

import com.networklib.http.impl.ProgressResponseBodyImpl;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;

public class DownloadProgressInterceptor implements Interceptor {
    private ProgressResponseBodyImpl.ProgressListener progressListener = new ProgressResponseBodyImpl.ProgressListener() {
        public void update(long bytesRead, long contentLength, boolean done) {
            System.out.println(bytesRead);
            System.out.println(contentLength);
            System.out.println(done);
            System.out.format("%d%% done\n", new Object[]{Long.valueOf(100L * bytesRead / contentLength)});
        }
    };

    public DownloadProgressInterceptor() {
    }

    public DownloadProgressInterceptor(ProgressResponseBodyImpl.ProgressListener progressListener) {
        if(progressListener != null) {
            this.progressListener = progressListener;
        }

    }

    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        return originalResponse.newBuilder().body(new ProgressResponseBodyImpl(originalResponse.body(), this.progressListener)).build();
    }
}
